package com.wy.cms.initconfig;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.wy.common.exception.BizException;
import com.wy.constant.ConfigConst;
import com.wy.domain.CmsRole;
import com.wy.domain.CmsUser;
import com.wy.protocol.ERRORCODE;
import com.wy.service.ICmsRoleService;
import com.wy.service.ICmsUserService;
import com.wy.service.ex.ICmsRoleExService;
import com.wy.service.ex.ICmsUserExService;
import com.wy.util.MD5Util;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;

public class CmsInitConfig {
	
	private static Element root = null;

	static{
		SAXReader sr = new SAXReader();
		try {
			InputStream in = CmsInitConfig.class.getClassLoader().getResourceAsStream(ConfigConst.CMS);
			Document doc = sr.read(in);
			root = doc.getRootElement();
			in.close();
			doc.clearContent();
		} catch (Exception e) {
			throw new BizException(ERRORCODE.FAIL.getCode(), ERRORCODE.FAIL.getMessage());
		}
	}
	
	
	public static void init() throws Exception{
		CmsInitConfig cmsInitConfig = new CmsInitConfig();
		cmsInitConfig.initAdminUser();
	}

	@Autowired
	private ICmsUserService cmsUserService;

	@Autowired
	private ICmsUserExService cmsUserExService;

	@Autowired
	private ICmsRoleService cmsRoleService;

	@Autowired
	private ICmsRoleExService cmsRoleExService;
	
	private void initAdminUser() throws Exception{

		cmsRoleExService.deleteAll();

		cmsUserExService.deleteAll();

		long currentTime = System.currentTimeMillis();
		
		Element role = root.element("role");

		CmsRole cmsRole = new CmsRole();

		cmsRole.setStatus(0);

		cmsRole.setName(role.attributeValue("name"));

		cmsRole.setCreateDate(currentTime);

		long roleId = cmsRoleService.insert(cmsRole);

		Element user = root.element("user");

		CmsUser cmsUser = new CmsUser();

		cmsUser.setCreateDate(currentTime);

		cmsUser.setStatus(0);

		cmsUser.setAccount(role.attributeValue("account"));

		cmsUser.setPassword(MD5Util.MD5Encode(role.attributeValue("password")));

		cmsUser.setRoleId(roleId);

		cmsUserService.insert(cmsUser);

	}
	
}
